<template>
  <el-cascader ref="cascader" :value="value" :props="categoryProp" placeholder="请选择分类" :disabled="disabled" :options="classifyList" clearable @input="inputHandler" @change="changeHandler" />
</template>

<script>
export default {
  name: 'ProductClass',
  props: {
    value: {
      required: true,
      type: [String, Number]
    },
    disabled: {
      type: Boolean,
      default: false
    },
    checkStrictly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      classifyList: [], // 商品分类列表
      children: []
    }
  },
  computed: {
    categoryProp() {
      const prop = {}
      if (!this.disabled) {
        prop['disabled'] = 'is_status'
      }
      if (this.checkStrictly) {
        prop['checkStrictly'] = true
      }
      return prop
    }
  },
  created() {
    const vm = this
    vm.getTreeList()
  },
  methods: {
    // 获取商品分类
    getTreeList() {
      const vm = this
      vm.$http.get(`/getListTree`).then((res) => {
        const filter = (arr, parentIds = []) => {
          return arr.map((e) => {
            e['value'] = e.id
            e['label'] = e.name
            // ids 用于 后续的 级联回填
            const ids = parentIds.concat()
            ids.push(e.id)
            e['ids'] = ids
            if (e.children) {
              e.children = filter(e.children, ids.concat())
            }
            return e
          })
        }
        const data = res.data.filter((e) => e.children && e.children.length > 0)
        vm.classifyList = filter(data)
        vm.children = vm.classifyList.reduce((list, e) => {
          list = list.concat(e.children)
          return list
        }, [])
      })
    },
    // input handler
    inputHandler(event) {},
    // change handler
    changeHandler(data) {
      const vm = this
      const id = data[1] || data[0] || ''
      const item = vm.classifyList.find(e => e.id === id)
      const childItem = vm.children.find((e) => e.id === id)
      vm.$emit('input', id)
      vm.$emit('change', childItem || item)
    }
  }
}
</script>

<style lang="less" scoped></style>
